<?php


namespace App\Api\Repositories;


use App\Api\Bases\BaseController;
use App\Api\Models\Member;
use App\Api\Models\PromotionBargain;
use App\Api\Models\PromotionBargainList;
use App\Api\Models\PromotionBargainRecord;
use App\Api\Services\JsonService;
use Illuminate\Support\Facades\DB;

class BargainBasic extends BaseController
{
    /**
     * @param $total string 砍价金额
     * @param $num int 砍价次数
     * @param $min float 最低可砍
     * @param $max float 最高可砍
     * @param int $level 成级
     * @return string
     */
    public static function bar($total, $num, $min, $max, $level = 0)
    {

        if ($num > 1) {
            $safe_total = ($total - ($num - 1) * $min) / ($num - 1);//随机安全上限
            if ($min < $safe_total) {//总价为最低价时，算出来的随机上限有可能会比最低价还低
                $bar = mt_rand((int)$min * 100, (int)$max * 100) / 100;
            }

            if ($bar > $total) {
                return self::bar($total, $num, $min, $max, $level + 1);
            }
            // 保留两位小数
            return $bar = sprintf("%.2f", $bar);   //砍掉的金额
        }

    }

    /**
     * 用户自己砍一刀
     * @param $memberId
     * @param $bargainId
     * @return array
     */
    public static function firstBar($memberId, $bargainId)
    {
        DB::beginTransaction();
        try {
            $user = Member::memberInfo($memberId,['nickname','avatar']);
            $field = ['first_bargain_price','cut_num','min_bar','max_bar'];
            $barGoods = PromotionBargain::bargainInfo($bargainId,$field);
            list($barPrice, $barNum, $minPrice, $maxPrice) = array_values($barGoods);
            $bar = BargainBasic::Bar($barPrice,$barNum,$minPrice,$maxPrice);
            $data = [
                'member_id' =>$memberId,
                'bargain_id' => $bargainId,
                'help_member_id' => $memberId,
                'money' => $bar,
                'nickname' => $user['nickname'],
                'headimg' => $user['avatar'],
                'old_price' => $barPrice - $bar,
                'old_num' => $barNum - 1,
                'bargain_time'=>date('Y-m-d H:i:s',time()),
            ];
            PromotionBargainRecord::saveBar($data);
            $data = [
                'member_id' => $memberId,
                'bargain_id' => $bargainId,
                'price' => $barPrice,
                'old_price' => $barPrice - $bar,
                'need_num'=>$barNum,
                'curr_num'=>1,
                'old_num' => $barNum - 1,
                'start_time'=>date('Y-m-d H:i:s',time()),
            ];
            PromotionBargainList::saveData($data);
            DB::commit();
            return JsonService::success('砍价发起成功',$data);
        }catch (\Exception $exception){
            DB::rollBack();
            return JsonService::fail($exception->getMessage());
        }
    }

    /**
     * 用户帮助砍价
     * @param $memberId
     * @param $bargainId
     * @param $helpMemberId
     * @return array
     */
    public static function helpBar($memberId, $bargainId,$helpMemberId)
    {
        DB::beginTransaction();
        try {
            $user = Member::memberInfo($helpMemberId,['nickname','avatar']);
            if (!$user) return JsonService::fail('请先注册,再砍价');
            $field = ['min_bar','max_bar'];
            $barGoods = PromotionBargain::bargainInfo( $bargainId,$field);
            list( $minPrice, $maxPrice) = array_values($barGoods);
            $where = [
              'member_id'=>$memberId,
              'bargain_id'=>$bargainId
            ];
            $field = ['old_price','old_num','curr_num'];
            $barList = PromotionBargainList::barList($where,$field);

            $bar = BargainBasic::bar($barList['old_price'], $barList['old_num'], $minPrice, $maxPrice); //砍价金额

            $data = [
                'member_id' => $memberId,
                'bargain_id' => $bargainId,
                'help_member_id' => $helpMemberId,
                'money' => $bar,
                'nickname' => $user['nickname'],
                'headimg' => $user['avatar'],
                'old_price' => $barList['old_price'] - $bar,
                'old_num' => $barList['old_num'] - 1,
                'bargain_time'=>date('Y-m-d H:i:s',time()),
            ];

            PromotionBargainRecord::saveBar($data);

            $data = [
                'old_price' => $barList['old_price'] - $bar,
                'old_num' => $barList['old_num'] - 1,
                'curr_num'=> $barList['curr_num']++,
            ];
            PromotionBargainList::saveData($data,$where);
            DB::commit();
            return JsonService::success('砍价成功',$data);
        }catch (\Exception $exception){
            DB::rollBack();
            return JsonService::fail($exception->getMessage());
        }


    }

    /**
     * 砍价最后一刀
     * @param $memberId
     * @param $bargainId
     * @param $helpMemberId
     * @return array
     */
    public static function lastBar($memberId, $bargainId,$helpMemberId)
    {
        DB::beginTransaction();
        try {
            $where = [
                'member_id' =>$memberId,
                'bargain_id'=>$bargainId
            ];
            $user = Member::memberInfo($helpMemberId,['nickname','avatar']);
            $oldPrice = PromotionBargainRecord::old_price($where);
            $where = [
                'member_id'=>$memberId,
                'bargain_id'=>$bargainId
            ];
            $field = ['old_price','old_num','curr_num'];
            $barList = PromotionBargainList::barList($where,$field);

            $data = [
                'member_id' => $memberId,
                'bargain_id' => $bargainId,
                'help_member_id' => $helpMemberId,
                'money' => $oldPrice,
                'nickname' => $user['nickname'],
                'headimg' => $user['avatar'],
                'old_price' => 0,
                'old_num' => 0
            ];
            PromotionBargainRecord::saveBar($data);

            $data = [
                'old_price' => 0,
                'old_num' => $barList['old_num'] - 1,
                'curr_num'=> $barList['curr_num']++,
            ];
            PromotionBargainList::saveData($data,$where);
            DB::commit();
            return JsonService::success('砍价成功',$data);
        }catch (\Exception $exception){
            DB::rollBack();
            return JsonService::fail($exception->getMessage());
        }

    }


    public static function oldTime($where)
    {
       $startTime = PromotionBargainList::startTime($where,'start_time');
       $bargainTime = PromotionBargainList::startTime($where,'bargain_time');

        $prefix  =  strtotime($startTime)+3600*$bargainTime;
       if (time() >$prefix) return false;
       return true;

    }
}
